package com.sunlong.jiangwei.web;

import com.sunlong.jiangwei.entity.result.Result;
import com.sunlong.jiangwei.util.MinioUtils;
import com.sunlong.jiangwei.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.util.Map;
import java.util.UUID;

import static com.sunlong.jiangwei.util.MinioUtils.getStream;

@RestController
@RequestMapping("/jiangwei/file")
@Slf4j
public class FileUploadController {

    @Autowired
    private MinioUtils minioUtils;

    @PostMapping("/upload")
    public Result<String> upload(@RequestBody Map<String,Object> map) throws Exception {
        if (!map.containsKey("file")){
            return ResultUtil.error("file参数缺失");
        }
        String type = (String) map.get("type");
        int mode = 0;
        if ("image/jpeg".equals(type)){
            mode = 1;
        }
        ByteArrayInputStream stream = getStream(map);
        String substring = UUID.randomUUID().toString().replace("-", "").substring(0, 10);
        String upload = minioUtils.upload("spudes", mode, stream, substring);
        return ResultUtil.data(upload);
    }
}
